package smartcampus.scjava.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtil {
    /**
     * 链接超时时间
     */
    private static final int COUN_TIME_OUT = 10 * 1000;
    /**
     * 读取超时时间
     */
    private static final int READ_TIME_OUT = 30 * 1000;
    /**
     * 边界符
     */
    private static final String BOUNDARY = "WebKitFormBoundary";
    private static final String PRE_FIX = ("\r\n--" + BOUNDARY + "\r\n");
    private static final String END_FIX = ("\r\n--" + BOUNDARY + "--\r\n");
    private static final String USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35";
    /**
     * 向指定服务器发送GET请求
     * */
    private static final int defTimeOut = 2500;
    public static String sendGet(String url,Integer timeOut) {
        BufferedReader in = null;
        try {
            if (timeOut == null || timeOut <= 0) {
                timeOut = defTimeOut;
            }
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", USER_AGENT);
            connection.setConnectTimeout(timeOut);
            connection.setReadTimeout(timeOut);
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response=getResult(connection.getInputStream());
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

    public static String sendPost(String url, Map<String, String> params, Integer timeOut) {
        BufferedReader in = null;
        try {
            if (timeOut == null || timeOut <= 0) {
                timeOut = defTimeOut;
            }
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", USER_AGENT);
            connection.setConnectTimeout(timeOut);
            connection.setReadTimeout(timeOut);

            // 设置请求体
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (postData.length() != 0) {
                    postData.append('&');
                }
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(param.getValue(), "UTF-8"));
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");

            connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            connection.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postDataBytes);
            out.flush();
            out.close();

            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response=getResult(connection.getInputStream());
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

    public static String sendPost2Login(String account,String pwd){
        String response = null;
        String url="http://119.84.149.56:20081/szcg/admin/basic_server/core/login/index";
        try {
            URL httpUrl=new URL(url);
            HttpURLConnection urlConnection=(HttpURLConnection)httpUrl.openConnection();
            urlConnection.setConnectTimeout(COUN_TIME_OUT);
            urlConnection.setReadTimeout(READ_TIME_OUT);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY+"; charset=utf-8");
            urlConnection.setRequestProperty("connection","keep-alive");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.connect();
            // ++++++++++++++++++++++++++++++++++
            // 写入参数
            // +++++++++++++++++++++++++++++++
            DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());

            String contentBody = PRE_FIX +
                    "Content-Disposition: form-data; name=\"account\"" + "\r\n" +
                    "Content-Type: text/plain; charset=UTF-8" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    account +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"pwd\"" + "\r\n" +
                    "Content-Type: text/plain; charset=UTF-8" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    pwd +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"code_id\"" + "\r\n" +
                    "Content-Type: text/plain; charset=UTF-8" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    true +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"_ajax\"" + "\r\n" +
                    "Content-Type: text/plain; charset=UTF-8" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    1 +
                    END_FIX;

            outputStream.write(contentBody.getBytes());
            outputStream.flush();
            if (urlConnection.getResponseCode() >= 200) {
                // 获取返回流
                response = getResult(urlConnection.getInputStream());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }
    public static String sendPost2GetList(String token){
        String response = null;
        String url="http://119.84.149.56:20081/szcg/admin/cases/info/list";
        try {
            URL httpUrl=new URL(url);
            HttpURLConnection urlConnection=(HttpURLConnection)httpUrl.openConnection();
            urlConnection.setConnectTimeout(COUN_TIME_OUT);
            urlConnection.setReadTimeout(READ_TIME_OUT);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY+"; charset=utf-8");
            urlConnection.setRequestProperty("connection","keep-alive");
            urlConnection.setRequestProperty("ses-token",token);
            urlConnection.setRequestProperty("sesToken",token);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.connect();
            // ++++++++++++++++++++++++++++++++++
            // 写入参数
            // +++++++++++++++++++++++++++++++
            DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());

            String contentBody = PRE_FIX +
                    "Content-Disposition: form-data; name=\"list_type\"" + "\r\n" +
                    "Content-Type: text/plain; charset=US-ASCII" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    14 +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"dispose_status\"" + "\r\n" +
                    "Content-Type: text/plain; charset=US-ASCII" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    1 +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"__page\"" + "\r\n" +
                    "Content-Type: text/plain; charset=US-ASCII" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    0 +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"__page_size\"" + "\r\n" +
                    "Content-Type: text/plain; charset=US-ASCII" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    100 +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"_ajax\"" + "\r\n" +
                    "Content-Type: text/plain; charset=US-ASCII" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    1 +
                    PRE_FIX +
                    "Content-Disposition: form-data; name=\"ses_token\"" + "\r\n" +
                    "Content-Type: text/plain; charset=US-ASCII" + "\r\n" +
                    "Content-Transfer-Encoding: 8bit" +
                    "\r\n" +
                    "\r\n" +
                    token +
                    END_FIX;
            outputStream.write(contentBody.getBytes());
            outputStream.flush();
            if (urlConnection.getResponseCode() >= 200) {
                // 获取返回流
                response = getResult(urlConnection.getInputStream());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }
    public static  String getResult(InputStream inputStream) {
        String result = "";
        ByteArrayOutputStream dataOutputStream;
        try {
            byte[] buf = new byte[1024];
            int n;
            dataOutputStream = new ByteArrayOutputStream();

            while (((n = inputStream.read(buf)) != -1)) {
                dataOutputStream.write(buf, 0, n);
            }
            dataOutputStream.toByteArray();
            result = dataOutputStream.toString("UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
//    public static List<String> toImgUrl(String file_info){
//        String imgUrl= StringUtils.substringBefore(StringUtils.substringAfter(file_info,"["),"]");
//        imgUrl=imgUrl.replace("{\"pic_url\":\"","http://119.84.149.56:20081/");
//        imgUrl=imgUrl.replace("\"}","");
//        String[] split = imgUrl.split(",");
//        return Arrays.asList(split);
//    }
//    public static String getImgUrl(List<String> imgUrls){
//        StringBuilder img= new StringBuilder();
//        for (String imgUrl:imgUrls){
//            String str=sendGet(imgUrl,3000);
//            System.out.println(str);
//            img.append(",").append(str);
//        }
//        return img.toString();
//    }

}

